package com.jiyinit.web.core.video.controller;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.jiyinit.core.framework.base.util.AESUtil;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.enums.OperationTypeConstant;
import com.jiyinit.web.core.business.service.UserServiceImpl;
import com.jiyinit.web.core.common.config.PropertyPlaceholderConfigurer;
import com.jiyinit.web.core.common.util.HttpClientUtil;
import com.jiyinit.web.core.common.util.MessagePush;
import com.jiyinit.web.core.mobile.util.FilesUtil;
import com.jiyinit.web.core.video.entity.TabCoreVideoUserEntity;
import com.jiyinit.web.core.video.service.VideoUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.web.core.video.dto.VideoRequest;
import com.jiyinit.web.core.video.entity.TabCoreVideoEntity;
import com.jiyinit.web.core.video.service.VideoServiceImpl;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jiyinit.web.core.mobile.controller.MuserAvatarController.getTodaySec;

@Controller
@RequestMapping(value = "mobile/video")
public class VideoController {

	private static final String msg = "系统异常";
	private static Logger logger = LoggerFactory.getLogger(VideoController.class);
	
	@Resource(name = "core.videoServiceImpl")
	private VideoServiceImpl service;

	@Resource(name = "core.videoUserServiceImpl")
	private VideoUserServiceImpl videoUserService;

    @Resource(name = "core.userServiceImpl")
    private UserServiceImpl userService;
	
	/**
	 * 查询
	 * @param req
	 * @param request_json
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getPageRows", method=RequestMethod.POST)
	public ResponseEntity<ResponseDto> getPageRows(HttpServletRequest req, String request_json){
		logger.info("传入参数: {}", request_json);
		VideoRequest request = JsonEntityTransform.json2Object(request_json, VideoRequest.class);
		logger.info("转换为obj之后的参数: {}", request.toString());
		//request.setLimit(Integer.MAX_VALUE);
		List<TabCoreVideoEntity> pag = service.findVlistByUserId(request.getUserId());
		return new ResponseEntity<>(ResponseDto.responseOK(pag), HttpStatus.OK);
	}

	/**
	 * 获取已经直播完成的视频列表
	 * @param req
	 * @param request_json
     * @return
     */
	@ResponseBody
	@RequestMapping(value = "/getVideoList")
	public ResponseEntity<ResponseDto> getVideoList(HttpServletRequest req, String request_json){
		logger.info("传入参数: {}", request_json);
		VideoRequest request = JsonEntityTransform.json2Object(request_json, VideoRequest.class);
		logger.info("转换为obj之后的参数: {}", request.toString());
		request.setIsClose("1");
		request.setLimit(10);
		PagingResult<TabCoreVideoEntity> forPage = service.findVideoListByUserId(request);
		return new ResponseEntity<>(ResponseDto.responseOK(forPage), HttpStatus.OK);
	}

	/**
	 * 查询异常关闭的直播接口
	 * @param req
	 * @param request_json
     * @return
     */
	@ResponseBody
	@RequestMapping(value = "/queryClose", method=RequestMethod.POST)
	public ResponseEntity<ResponseDto> queryClose(HttpServletRequest req, String request_json){
		logger.info("传入参数: {}", request_json);
		VideoRequest request = JsonEntityTransform.json2Object(request_json, VideoRequest.class);
		logger.info("转换为obj之后的参数: {}", request.toString());
		List<TabCoreVideoEntity> rooms = service.findOpenRoom(request.getUserId());
		return new ResponseEntity<>(ResponseDto.responseOK(rooms), HttpStatus.OK);
	}
	
	/**
	 * 添加
	 * @param req
	 * @param request_json
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/toAdd", method=RequestMethod.POST)
	public ResponseEntity<ResponseDto> add(HttpServletRequest req, String request_json){
		logger.info("传入参数: {}", request_json);
		TabCoreVideoEntity entity = JsonEntityTransform.json2Object(request_json, TabCoreVideoEntity.class);
		if(Check.isNullStrStrict(entity.getAttr1())){
			return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("视频会议标题不能为空!"), HttpStatus.OK);
		}else if(entity.getAttr1().length() > 15){
			return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("视频会议标题不能超过15个字!"), HttpStatus.OK);
		}
		if(Check.isNullStrStrict(entity.getParticipantIds())){
			return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("视频会议参与人不能为空!"), HttpStatus.OK);
		}

		try {
			saveImgForVideo(entity, request_json, req);//保存会议封面
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("视频封面上传失败!");
			return new ResponseEntity<>(ResponseDto.responseFail(msg),HttpStatus.OK);
		}
		entity.setViHomeId(makeViHomeId(entity.getSponsorId()));
		entity.setViOpenTime(new Date());
		entity.setIsClose("0");
		logger.info("转换为obj之后的参数: {}", entity.toString());

		int i = 0;
		int num = 0;
		if(!Check.isNullObj(entity)){
			i = service.add(entity);
			String ids = entity.getParticipantIds();
			String[] idArray = ids.split(",");
			for (int j = 0; j < idArray.length; j++) {
				if(!Check.isNullStrStrict(idArray[j])){
					TabCoreVideoUserEntity videoUser = new TabCoreVideoUserEntity();
					videoUser.setViId(entity.getId());
					videoUser.setViHomeId(entity.getViHomeId());
					videoUser.setUserId(Integer.valueOf(idArray[j]));
					num += videoUserService.add(videoUser);
				}
            }
            pushMsg(entity.getSponsorId(), idArray);
            logger.info("添加视频房间:{"+i+"}, 添加关联用户: {"+num+"}");
		}
    	if (i>0) {
    		return new ResponseEntity<>(ResponseDto.responseOK(entity), HttpStatus.OK);
    	}
    	return new ResponseEntity<>(ResponseDto.responseFail(msg),HttpStatus.OK);
	}
	
	/**
	 * 修改
	 * @param req
	 * @param request_json
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/update", method=RequestMethod.POST)
	public ResponseEntity<ResponseDto> update(HttpServletRequest req, String request_json){
		logger.info("传入参数: {}", request_json);
		TabCoreVideoEntity entity = JsonEntityTransform.json2Object(request_json, TabCoreVideoEntity.class);
        TabCoreVideoEntity videoEntity = new TabCoreVideoEntity();
        videoEntity.setId(entity.getId());
        videoEntity.setIsClose("1");
		logger.info("转换为obj之后的参数: {}", videoEntity.toString());
		int i = 0;
		if(!Check.isNullObj(entity)){
			i = service.update(videoEntity);
		}
		if (i>0) {
    		return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
    	}
    	return new ResponseEntity<>(ResponseDto.responseFail(msg),HttpStatus.OK);
	}


	/**
	 * 删除
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/delete", method=RequestMethod.POST)
	public ResponseEntity<ResponseDto> delete(HttpServletRequest req) {
		String str = req.getParameter("ids");
		int i = 0;
		if(!Check.isNullStrStrict(str)){
			String[] strs = str.split(",");
			for (int j = 0; j < strs.length; j++) {
				int id = Integer.valueOf(strs[i]);
				i += service.delete(id);
			}
		}
		if (i>0) {
    		return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
    	}
    	return new ResponseEntity<>(ResponseDto.responseFail(msg),HttpStatus.OK);
	}
	
	@RequestMapping(value = "/Playback")
	public String test(HttpServletRequest req, String request_json) {
		logger.info("传入参数: {}", request_json);
		VideoRequest request = JsonEntityTransform.json2Object(request_json, VideoRequest.class);
		logger.info("转换为obj之后的参数: {}", request.toString());
		String key = getEncryptKey("FLV_KEY");
		String viHomeId = request.getViHomeId();
		viHomeId = AESUtil.encrypt(key, viHomeId);
		req.setAttribute("viHomeId", viHomeId);
		return "video";
	}

	@RequestMapping(value = "/getFlv")
	public void getFlv(HttpServletRequest request, HttpServletResponse response){
		String viHomeId = request.getParameter("viHomeId");
		String key = getEncryptKey("FLV_KEY");
		viHomeId = AESUtil.decrypt(key, viHomeId);

		String path = getFlvPath(viHomeId);
		File file = new File(path);
		try {
			FileInputStream fis = new FileInputStream(file);
			ServletOutputStream out = response.getOutputStream();
			response.setContentType("video/flv");
			byte[] bytes = new byte[1024];
			while (fis.read(bytes) != -1){
				out.write(bytes);
			}
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取视频绝对路径
	 * @param viHomeId
	 * @return
     */
	public String getFlvPath(String viHomeId){
		String flv_url = getProperties("FLV_URL");
		String sep = System.getProperty("file.separator");
		return flv_url + sep + viHomeId+".flv";
	}

	/**
	 * 获取加密key
	 * @param key
	 * @return
     */
	public String getEncryptKey(String key){
		String value = (String) PropertyPlaceholderConfigurer.getContextProperty(key);
		if(Check.isNullStrStrict(value)){
			return "FLV6768";
		}
		return key;
	}

	/**
	 * 获取配置文件参数
	 * @param key
	 * @return
     */
	public String getProperties(String key){
		return (String) PropertyPlaceholderConfigurer.getContextProperty(key);
	}

    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    public TabCoreUserEntity getUserInfos(Integer userId){
        return userService.getUserInfoByUserId(userId);
    }

	/**
	 * 生成房间id
	 * @param userId
	 * @return
     */
	public String makeViHomeId(String userId){
		SimpleDateFormat sdf = new SimpleDateFormat("_yyyyMMdd_HHmmss_");
		String format = sdf.format(new Date());
		String random = UUID.randomUUID().toString().substring(2, 6);
		return userId+format+random;
	}

	/**
	 * 发送极光推送
	 * @param userId
	 * @param sendUser
     */
	public void pushMsg(String userId, String[] sendUser){
		//极光推送
		Map<String, String> returnStr = new HashMap<>();
		//returnStr.put("taskId",String.valueOf(task.getTaskId()));
		returnStr.put("title", "视频会议");
		returnStr.put("userId", userId);
		//returnStr.put("createUid",String.valueOf(task.getCreateUid()));
		//returnStr.put("toUserId", sendUser[0]);
		returnStr.put("type", OperationTypeConstant.VIDEO_PUSH);
		returnStr.put("content",  getUserInfos(Integer.valueOf(userId)).getUserName()+"邀请你参加视频会议");
		String[] sendUsers = sendUser;
		new MessagePush(returnStr,sendUsers);
	}

	/**
	 * 保存视频封面
	 * @param vobj
	 * @param request_json
	 * @param request
	 * @throws IOException
     */
	public void saveImgForVideo(TabCoreVideoEntity vobj, String request_json, HttpServletRequest request) throws IOException {
		JSONObject requestObj = JSONObject.parseObject(request_json);

		Object imgStr  = requestObj.get("attr2");
		String picName = vobj.getSponsorId() + "_" + getTodaySec() + "_"+ UUID.randomUUID().toString().substring(2, 6) + ".jpg";
		String picPath = (String) PropertyPlaceholderConfigurer.getContextProperty("VIDEO_COVER");
		String imgFile = request.getSession().getServletContext().getRealPath("") + "/" + picPath + picName;
		BASE64Decoder decoder = new BASE64Decoder();
		// Base64解码
		byte[] b = decoder.decodeBuffer(imgStr.toString());
		for (int i = 0; i < b.length; ++i) {
			if (b[i] < 0) {// 调整异常数据
				b[i] += 256;
			}
		}
		// 生成jpeg图片
		String imgFilePath = imgFile;
		FilesUtil.createDirectoryAndFile(imgFilePath);
		OutputStream out = new FileOutputStream(imgFilePath);
		out.write(b);
		out.flush();
		out.close();
		vobj.setAttr2(picName);
	}


}
